<template>
  <div class="chat-input-container">
    <div class="input-wrapper">
      <!-- 文件上传按钮 -->
      <!-- <button 
        class="attachment-btn"
        @click="triggerFileUpload"
        title="上传文件"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
        </svg>
      </button> -->

      <!-- 文本输入区域 -->
      <div class="input-area">
        <textarea
          ref="textareaRef"
          v-model="inputText"
          :placeholder="placeholder"
          :disabled="disabled"
          class="message-input"
          rows="1"
          @keydown="handleKeydown"
          @input="adjustHeight"
        />
        
        <!-- 字符计数 -->
        <div v-if="showCharCount" class="char-count">
          {{ inputText.length }}/{{ maxLength }}
        </div>
      </div>

      <!-- 发送/停止按钮 -->
      <button 
        v-if="!loading"
        class="send-btn"
        :class="{ 'active': canSend }"
        :disabled="!canSend"
        @click="handleSend"
        title="发送消息 (Ctrl+Enter)"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
        </svg>
      </button>
      
      <!-- 停止生成按钮 -->
      <button 
        v-else
        class="stop-btn"
        @click="handleStop"
        title="停止生成"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 9h6v6H9V9z" />
        </svg>
      </button>
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInputRef"
      type="file"
      multiple
      accept="image/*,.pdf,.doc,.docx,.txt"
      class="hidden"
      @change="handleFileSelect"
    />

    <!-- 已选择的文件列表 -->
    <div v-if="selectedFiles.length > 0" class="selected-files">
      <div 
        v-for="(file, index) in selectedFiles" 
        :key="index"
        class="file-item"
      >
        <div class="file-info">
          <svg class="w-4 h-4 text-gray-500" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clip-rule="evenodd" />
          </svg>
          <span class="file-name">{{ file.name }}</span>
          <span class="file-size">({{ formatFileSize(file.size) }})</span>
        </div>
        <button 
          @click="removeFile(index)"
          class="remove-file-btn"
          title="移除文件"
        >
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
    </div>

    <!-- 提示信息 -->
    <div v-if="showHint" class="input-hint">
      按 Ctrl+Enter 发送消息，Shift+Enter 换行
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'

interface Props {
  placeholder?: string
  disabled?: boolean
  loading?: boolean
  maxLength?: number
  showCharCount?: boolean
  showHint?: boolean
  controlClear?: number
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '输入您的消息...',
  disabled: false,
  loading: false,
  maxLength: 2000,
  showCharCount: false,
  showHint: true,
  controlClear: 0
})

const emit = defineEmits<{
  send: [message: string, files: File[]]
  input: [value: string]
  stop: []
}>()

const inputText = ref('')
const selectedFiles = ref<File[]>([])
const textareaRef = ref<HTMLTextAreaElement>()
const fileInputRef = ref<HTMLInputElement>()

const canSend = computed(() => {
  return !props.disabled && !props.loading && (inputText.value.trim() || selectedFiles.value.length > 0)
})

// 自动调整文本框高度
const adjustHeight = () => {
  nextTick(() => {
    if (textareaRef.value) {
      textareaRef.value.style.height = 'auto'
      textareaRef.value.style.height = Math.min(textareaRef.value.scrollHeight, 120) + 'px'
    }
  })
}

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    if (event.ctrlKey || event.metaKey) {
      // Ctrl+Enter 发送消息
      event.preventDefault()
      handleSend()
    } else if (!event.shiftKey) {
      // Enter 发送消息（如果不是 Shift+Enter）
      event.preventDefault()
      handleSend()
    }
    // Shift+Enter 允许换行，不做处理
  }
}

// 发送消息
const handleSend = () => {
  if (!canSend.value) return
  
  const message = inputText.value.trim()
  const files = [...selectedFiles.value]
  
  if (message || files.length > 0) {
    emit('send', message, files)
    inputText.value = ''
    selectedFiles.value = []
    adjustHeight()
  }
}

// 停止生成
const handleStop = () => {
  emit('stop')
}

// 触发文件上传
const triggerFileUpload = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files) {
    const newFiles = Array.from(target.files)
    selectedFiles.value.push(...newFiles)
    target.value = '' // 清空input，允许重复选择同一文件
  }
}

// 移除文件
const removeFile = (index: number) => {
  selectedFiles.value.splice(index, 1)
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 监听输入变化
watch(inputText, (value) => {
  emit('input', value)
  adjustHeight()
})

// 监听清空控制
watch(() => props.controlClear, (newVal) => {
  if (newVal && newVal > 0) {
    inputText.value = ''
    selectedFiles.value = []
    adjustHeight()
  }
})

// 初始化高度
nextTick(() => {
  adjustHeight()
})
</script>

<style scoped>
.chat-input-container {
  /* @apply p-6; */
  max-width: 1000px;
  margin: 0 auto;
  /* 确保输入区域背景一致 */
  /* background: linear-gradient(to bottom, #f8fafc 0%, #f1f5f9 100%); */
  /* 防止滚动穿透 */
  position: relative;
  z-index: 20;
}

.input-wrapper {
  @apply flex items-end gap-3 bg-white rounded-3xl p-4 border border-gray-100;
  max-width: 950px;
  margin: 0 auto;
  /* 添加悬浮阴影效果 */
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  /* 悬浮时的动态效果 */
  transform: translateY(0);
  /* 确保输入框背景完全覆盖 */
  position: relative;
}

.input-wrapper:hover {
  @apply shadow-2xl;
  transform: translateY(-2px);
  box-shadow: 0 20px 35px -5px rgba(0, 0, 0, 0.15), 0 15px 20px -6px rgba(0, 0, 0, 0.1);
}

.attachment-btn {
  @apply flex-shrink-0 p-2.5 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-xl transition-all duration-200;
}

.attachment-btn:hover {
  transform: scale(1.05);
}

.input-area {
  @apply flex-1 relative;
}

.message-input {
  @apply w-full bg-transparent border-none outline-none resize-none text-gray-900 placeholder-gray-500 text-base leading-relaxed;
  min-height: 24px;
  max-height: 120px;
  font-family: inherit;
}

.char-count {
  @apply absolute bottom-0 right-0 text-xs text-gray-400 bg-white px-2 py-1 rounded-lg shadow-sm;
}

.send-btn {
  @apply flex-shrink-0 p-2.5 text-gray-400 hover:text-gray-600 rounded-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed;
}

.send-btn:hover:not(:disabled) {
  transform: scale(1.05);
}

.send-btn.active {
  @apply text-white bg-blue-500 hover:bg-blue-600 shadow-lg;
  transform: scale(1.05);
}

.send-btn.active:hover {
  @apply bg-blue-600;
  transform: scale(1.08);
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.4);
}

.stop-btn {
  @apply flex-shrink-0 p-2.5 text-white bg-red-500 hover:bg-red-600 rounded-xl transition-all duration-200 shadow-lg;
  transform: scale(1.05);
}

.stop-btn:hover {
  @apply bg-red-600;
  transform: scale(1.08);
  box-shadow: 0 8px 20px rgba(239, 68, 68, 0.4);
}

.selected-files {
  @apply mt-4 space-y-2;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.file-item {
  @apply flex items-center justify-between bg-white rounded-2xl p-3 border border-gray-100 shadow-md transition-all duration-200;
}

.file-item:hover {
  @apply shadow-lg;
  transform: translateY(-1px);
}

.file-info {
  @apply flex items-center gap-3 flex-1 min-w-0;
}

.file-name {
  @apply text-sm text-gray-700 truncate font-medium;
}

.file-size {
  @apply text-xs text-gray-500 flex-shrink-0;
}

.remove-file-btn {
  @apply p-1.5 text-gray-400 hover:text-red-500 rounded-lg transition-all duration-200;
}

.remove-file-btn:hover {
  transform: scale(1.1);
  @apply bg-red-50;
}

.input-hint {
  @apply mt-3 text-xs text-gray-500 text-center;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.hidden {
  @apply sr-only;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-input-container {
    @apply p-4;
  }
  
  .input-wrapper {
    @apply rounded-2xl p-3;
    /* 移动端减少阴影 */
    box-shadow: 0 8px 20px -5px rgba(0, 0, 0, 0.1), 0 6px 8px -6px rgba(0, 0, 0, 0.1);
  }
  
  .input-wrapper:hover {
    /* 移动端悬浮效果减弱 */
    transform: translateY(0);
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.12), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
  }
  
  .message-input {
    @apply text-base;
  }
  
  .send-btn, .stop-btn {
    @apply p-2;
  }
  
  /* 移动端禁用变换效果 */
  .attachment-btn:hover,
  .send-btn:hover:not(:disabled),
  .remove-file-btn:hover {
    transform: none;
  }
  
  .send-btn.active:hover,
  .stop-btn:hover {
    transform: none;
  }
}

/* 平滑进入动画 */
@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.input-wrapper {
  animation: slideUp 0.3s ease-out;
}
</style> 